# -*- coding: utf-8 -*-
from django.shortcuts import render
# 基于类实现需要继承的view
from django.views.generic.base import View
# Django自带的用户验证,login
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
# 并集运算
from django.db.models import Q
from .forms import LoginForms, RegisterForms
# 进行密码加密
from django.contrib.auth.hashers import make_password
from .models import UserProfile


# Create your views here.

class CustomBackend(ModelBackend):
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            # 查询用户
            # 不希望用户存在两个，get只能有一个。两个是get失败的一种原因 Q为使用并集查询
            user = UserProfile.objects.get(Q(username=username) | Q(email=username))
            # django的后台中密码加密：所以不能password==password
            # UserProfile继承的AbstractUser中有def check_password(self,
            # raw_password):
            if user.check_password(password):
                return user
            else:
                return None
        except Exception as e:
            return None


# 登陆模块
class LoinView(View):
    # 跳转到登录页面
    def get(self, request):
        redirect_url = request.GET.get('next', '')
        return render(request, 'userLogin.html', {'redirect_url': redirect_url})

    def post(self, request):
        login_form = LoginForms(request.POST)
        if login_form.is_valid():
            # 获取提交的参数
            user_name = request.POST.get('username', '')
            pass_word = request.POST.get('password', '')
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                login(request, user)
                print("登录成功")
                pass
            else:
                return render(request, "userLogin.html", {"msg": "用户名或密码错误！"})
        else:
            return render(request, "userLogin.html", {'loin_form': login_form})


# 退出登录
class LogOutView(View):
    def get(self, request):
        logout(request)
        return render(request, "userLogin.html")


class RegisterView(View):
    def get(self, request):
        register_form = RegisterForms()
        return render(request, "register.html", {'register_form': register_form})

    def post(self, request):
        register_form = RegisterForms(request.POST)
        if register_form.is_valid():
            # 用户名和邮箱 查重
            user_name = request.POST.get("username", "")
            pass_word = request.POST.get("password", "")
            emails = request.POST.get("email", "")
            bool = False
            error_username = ""
            error_email = ""
            if UserProfile.objects.filter(username=user_name):
                bool = True
                error_username = "用户名已存在"
            if UserProfile.objects.filter(email=emails):
                bool = True
                error_email = "邮箱已存在"
            if bool:
                return render(request, 'register.html', {"error_email": error_email, "error_username": error_username,
                                                         'register_form': register_form})
            # 实例化一个user_profile对象，将前台值存入
            user_profile = UserProfile()
            user_profile.username = user_name
            user_profile.email = emails

            # 默认激活状态为false
            user_profile.is_active = False

            # 加密password进行保存
            user_profile.password = make_password(pass_word)
            user_profile.save()
            # 保存成功 跳转到 登录页面
            return render(request, "userLogin.html")
        else:
            return render(request, 'register.html', {"register_form": register_form})
